const LOCAL_KEY = 'todomvc';

/**
 *  生成一个随机id 的函数
 */
export function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x'? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

/**
 *  获取目前所有的任务
 */
export function fetch() {
    const result = localStorage.getItem(LOCAL_KEY);
    if(result) {
        return JSON.parse(result)
    }else{
        return []
    }
}

/**
 * 保存所有任务
 * @param {*} todos 任务列表
 */
export function save(todos) {
    localStorage.setItem(LOCAL_KEY,JSON.stringify(todos))
}

/**
 * 数据处理函数
 */
export function filter(todos, visibility= 'all') {
    if(visibility === 'all') {
        return todos
    }else if(visibility === 'active') {
        return todos.filter((t)=> !t.completed);
    }else if(visibility === 'completed') {
        return todos.filter((t) => t.completed);
    }
    throw new Error("invalid visibility value");
}